{% extends 'base.html' %}
{% load static %}

{% block title %}任务详情 - CFS Web System{% endblock %}

{% block extra_css %}
<style>
.task-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 8px;
    padding: 30px;
    margin-bottom: 30px;
}

.task-status {
    display: inline-block;
    padding: 6px 12px;
    border-radius: 20px;
    font-size: 0.875rem;
    font-weight: 500;
}

.task-status.pending {
    background: #fff3cd;
    color: #856404;
}

.task-status.processing {
    background: #cce5ff;
    color: #004085;
}

.task-status.completed {
    background: #d4edda;
    color: #155724;
}

.task-status.failed {
    background: #f8d7da;
    color: #721c24;
}

.task-status.cancelled {
    background: #e2e3e5;
    color: #383d41;
}

.priority-badge {
    display: inline-block;
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 0.75rem;
    font-weight: 500;
}

.priority-badge.low {
    background: #e2e3e5;
    color: #495057;
}

.priority-badge.medium {
    background: #fff3cd;
    color: #856404;
}

.priority-badge.high {
    background: #f8d7da;
    color: #721c24;
}

.priority-badge.urgent {
    background: #721c24;
    color: white;
}

.progress-section {
    background: white;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    margin-bottom: 20px;
}

.progress-bar-custom {
    height: 8px;
    border-radius: 4px;
    background: #e9ecef;
    overflow: hidden;
    margin: 10px 0;
}

.progress-fill {
    height: 100%;
    background: linear-gradient(90deg, #28a745, #20c997);
    border-radius: 4px;
    transition: width 0.3s ease;
}

.step-indicator {
    display: flex;
    justify-content: space-between;
    margin: 20px 0;
}

.step {
    flex: 1;
    text-align: center;
    position: relative;
}

.step::before {
    content: '';
    position: absolute;
    top: 15px;
    left: 50%;
    right: -50%;
    height: 2px;
    background: #dee2e6;
    z-index: 1;
}

.step:last-child::before {
    display: none;
}

.step.completed::before {
    background: #28a745;
}

.step-circle {
    width: 30px;
    height: 30px;
    border-radius: 50%;
    background: #dee2e6;
    color: #6c757d;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 8px;
    position: relative;
    z-index: 2;
    font-size: 0.875rem;
    font-weight: 500;
}

.step.completed .step-circle {
    background: #28a745;
    color: white;
}

.step.active .step-circle {
    background: #007bff;
    color: white;
}

.step-label {
    font-size: 0.75rem;
    color: #6c757d;
}

.step.completed .step-label,
.step.active .step-label {
    color: #333;
    font-weight: 500;
}

.info-card {
    background: white;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    margin-bottom: 20px;
}

.info-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 0;
    border-bottom: 1px solid #f1f3f4;
}

.info-row:last-child {
    border-bottom: none;
}

.info-label {
    font-weight: 500;
    color: #495057;
}

.info-value {
    color: #6c757d;
}

.file-list {
    background: white;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.file-item {
    display: flex;
    align-items: center;
    padding: 15px 20px;
    border-bottom: 1px solid #f1f3f4;
    transition: background 0.2s;
}

.file-item:hover {
    background: #f8f9fa;
}

.file-item:last-child {
    border-bottom: none;
}

.file-icon {
    width: 40px;
    height: 40px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 15px;
    font-size: 1.2rem;
}

.file-icon.excel {
    background: #e8f5e8;
    color: #28a745;
}

.file-icon.csv {
    background: #e3f2fd;
    color: #2196f3;
}

.file-icon.txt {
    background: #f3e5f5;
    color: #9c27b0;
}

.file-info {
    flex: 1;
    min-width: 0;
}

.file-name {
    font-weight: 500;
    margin-bottom: 4px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.file-meta {
    font-size: 0.875rem;
    color: #6c757d;
}

.file-actions {
    display: flex;
    gap: 8px;
}

.log-container {
    background: #1e1e1e;
    color: #d4d4d4;
    border-radius: 8px;
    padding: 20px;
    font-family: 'Consolas', 'Monaco', monospace;
    font-size: 0.875rem;
    line-height: 1.4;
    max-height: 400px;
    overflow-y: auto;
    margin-bottom: 20px;
}

.log-line {
    margin-bottom: 4px;
    word-break: break-all;
}

.log-line.info {
    color: #4fc3f7;
}

.log-line.warning {
    color: #ffb74d;
}

.log-line.error {
    color: #f48fb1;
}

.log-line.success {
    color: #81c784;
}

.timeline {
    position: relative;
    padding-left: 30px;
}

.timeline::before {
    content: '';
    position: absolute;
    left: 15px;
    top: 0;
    bottom: 0;
    width: 2px;
    background: #dee2e6;
}

.timeline-item {
    position: relative;
    margin-bottom: 20px;
}

.timeline-item::before {
    content: '';
    position: absolute;
    left: -23px;
    top: 8px;
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: #007bff;
    border: 2px solid white;
    box-shadow: 0 0 0 2px #007bff;
}

.timeline-content {
    background: white;
    border-radius: 8px;
    padding: 15px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.timeline-time {
    font-size: 0.75rem;
    color: #6c757d;
    margin-bottom: 5px;
}

.timeline-title {
    font-weight: 500;
    margin-bottom: 5px;
}

.timeline-desc {
    font-size: 0.875rem;
    color: #6c757d;
}

.action-buttons {
    position: sticky;
    bottom: 20px;
    background: white;
    padding: 15px;
    border-radius: 8px;
    box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
    margin-top: 20px;
}

@media (max-width: 768px) {
    .task-header {
        padding: 20px;
        text-align: center;
    }
    
    .step-indicator {
        flex-direction: column;
        gap: 10px;
    }
    
    .step::before {
        display: none;
    }
    
    .info-row {
        flex-direction: column;
        align-items: flex-start;
        gap: 4px;
    }
    
    .file-item {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
    }
    
    .file-actions {
        width: 100%;
        justify-content: flex-end;
    }
}
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 任务头部信息 -->
    <div class="task-header">
        <div class="row align-items-center">
            <div class="col-md-8">
                <h2 class="mb-2" id="taskName">任务名称</h2>
                <p class="mb-3 opacity-75" id="taskDescription">任务描述</p>
                <div class="d-flex align-items-center gap-3">
                    <span class="task-status" id="taskStatus">处理中</span>
                    <span class="priority-badge" id="taskPriority">中等</span>
                    <span class="text-white-50">
                        <i class="fas fa-clock me-1"></i>
                        <span id="taskCreatedAt">2024-01-01 10:00</span>
                    </span>
                </div>
            </div>
            <div class="col-md-4 text-md-end">
                <div class="task-progress-info">
                    <div class="h4 mb-1" id="taskProgress">65%</div>
                    <div class="small opacity-75">完成进度</div>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-lg-8">
            <!-- 任务进度 -->
            <div class="progress-section">
                <h5 class="mb-3">
                    <i class="fas fa-tasks me-2"></i>任务进度
                </h5>
                
                <div class="progress-bar-custom">
                    <div class="progress-fill" id="progressBar" style="width: 0%"></div>
                </div>
                
                <div class="step-indicator" id="stepIndicator">
                    <div class="step" data-step="1">
                        <div class="step-circle">1</div>
                        <div class="step-label">文件上传</div>
                    </div>
                    <div class="step" data-step="2">
                        <div class="step-circle">2</div>
                        <div class="step-label">数据解析</div>
                    </div>
                    <div class="step" data-step="3">
                        <div class="step-circle">3</div>
                        <div class="step-label">模板应用</div>
                    </div>
                    <div class="step" data-step="4">
                        <div class="step-circle">4</div>
                        <div class="step-label">数据生成</div>
                    </div>
                    <div class="step" data-step="5">
                        <div class="step-circle">5</div>
                        <div class="step-label">完成</div>
                    </div>
                </div>
                
                <div class="mt-3">
                    <small class="text-muted" id="progressMessage">正在处理数据...</small>
                </div>
            </div>
            
            <!-- 任务日志 -->
            <div class="info-card">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h5 class="mb-0">
                        <i class="fas fa-terminal me-2"></i>执行日志
                    </h5>
                    <div class="btn-group btn-group-sm">
                        <button type="button" class="btn btn-outline-secondary" id="refreshLogs">
                            <i class="fas fa-sync-alt"></i>
                        </button>
                        <button type="button" class="btn btn-outline-secondary" id="downloadLogs">
                            <i class="fas fa-download"></i>
                        </button>
                        <button type="button" class="btn btn-outline-secondary" id="clearLogs">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </div>
                
                <div class="log-container" id="logContainer">
                    <div class="log-line info">[2024-01-01 10:00:00] 任务开始执行</div>
                    <div class="log-line info">[2024-01-01 10:00:01] 正在上传文件...</div>
                    <div class="log-line success">[2024-01-01 10:00:05] 文件上传完成</div>
                    <div class="log-line info">[2024-01-01 10:00:06] 开始解析数据...</div>
                </div>
                
                <div class="form-check mt-3">
                    <input class="form-check-input" type="checkbox" id="autoRefreshLogs" checked>
                    <label class="form-check-label" for="autoRefreshLogs">
                        自动刷新日志 (每5秒)
                    </label>
                </div>
            </div>
            
            <!-- 任务时间线 -->
            <div class="info-card">
                <h5 class="mb-3">
                    <i class="fas fa-history me-2"></i>执行时间线
                </h5>
                
                <div class="timeline" id="taskTimeline">
                    <!-- 时间线项目将通过JavaScript动态加载 -->
                </div>
            </div>
        </div>
        
        <div class="col-lg-4">
            <!-- 任务信息 -->
            <div class="info-card">
                <h5 class="mb-3">
                    <i class="fas fa-info-circle me-2"></i>任务信息
                </h5>
                
                <div class="info-row">
                    <span class="info-label">任务ID:</span>
                    <span class="info-value" id="taskId">-</span>
                </div>
                <div class="info-row">
                    <span class="info-label">创建时间:</span>
                    <span class="info-value" id="taskCreatedTime">-</span>
                </div>
                <div class="info-row">
                    <span class="info-label">开始时间:</span>
                    <span class="info-value" id="taskStartTime">-</span>
                </div>
                <div class="info-row">
                    <span class="info-label">完成时间:</span>
                    <span class="info-value" id="taskEndTime">-</span>
                </div>
                <div class="info-row">
                    <span class="info-label">执行时长:</span>
                    <span class="info-value" id="taskDuration">-</span>
                </div>
                <div class="info-row">
                    <span class="info-label">使用模板:</span>
                    <span class="info-value" id="taskTemplate">-</span>
                </div>
                <div class="info-row">
                    <span class="info-label">输出格式:</span>
                    <span class="info-value" id="taskOutputFormat">-</span>
                </div>
            </div>
            
            <!-- 源文件 -->
            <div class="info-card">
                <h5 class="mb-3">
                    <i class="fas fa-file-upload me-2"></i>源文件
                </h5>
                
                <div class="file-list" id="sourceFiles">
                    <!-- 源文件列表将通过JavaScript动态加载 -->
                </div>
            </div>
            
            <!-- 结果文件 -->
            <div class="info-card">
                <h5 class="mb-3">
                    <i class="fas fa-file-download me-2"></i>结果文件
                </h5>
                
                <div class="file-list" id="resultFiles">
                    <!-- 结果文件列表将通过JavaScript动态加载 -->
                </div>
                
                <div class="text-center py-3" id="noResultFiles" style="display: none;">
                    <i class="fas fa-hourglass-half text-muted fa-2x mb-2"></i>
                    <div class="text-muted">任务完成后将显示结果文件</div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 操作按钮 -->
    <div class="action-buttons">
        <div class="d-flex justify-content-between align-items-center">
            <div>
                <button type="button" class="btn btn-outline-secondary" onclick="history.back()">
                    <i class="fas fa-arrow-left me-1"></i>返回
                </button>
            </div>
            <div class="d-flex gap-2">
                <button type="button" class="btn btn-outline-info" id="exportTask">
                    <i class="fas fa-file-export me-1"></i>导出任务
                </button>
                <button type="button" class="btn btn-outline-warning" id="retryTask" style="display: none;">
                    <i class="fas fa-redo me-1"></i>重试任务
                </button>
                <button type="button" class="btn btn-outline-danger" id="cancelTask" style="display: none;">
                    <i class="fas fa-stop me-1"></i>取消任务
                </button>
                <button type="button" class="btn btn-success" id="downloadResults" style="display: none;">
                    <i class="fas fa-download me-1"></i>下载结果
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 取消任务确认模态框 -->
<div class="modal fade" id="cancelTaskModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-exclamation-triangle text-warning me-2"></i>确认取消任务
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>确定要取消这个任务吗？</p>
                <div class="alert alert-warning">
                    <i class="fas fa-info-circle me-2"></i>
                    <strong>注意：</strong>取消后的任务无法恢复，已处理的数据将会丢失。
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="confirmCancelTask">
                    <i class="fas fa-stop me-1"></i>确认取消
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 重试任务模态框 -->
<div class="modal fade" id="retryTaskModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-redo text-warning me-2"></i>重试任务
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>确定要重试这个任务吗？</p>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="useOriginalFiles" checked>
                    <label class="form-check-label" for="useOriginalFiles">
                        使用原始文件
                    </label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="useOriginalSettings" checked>
                    <label class="form-check-label" for="useOriginalSettings">
                        使用原始设置
                    </label>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-warning" id="confirmRetryTask">
                    <i class="fas fa-redo me-1"></i>确认重试
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
$(document).ready(function() {
    // 全局变量
    let taskId = getTaskIdFromUrl();
    let autoRefreshInterval;
    let logRefreshInterval;
    
    // 初始化
    initializePage();
    
    function initializePage() {
        loadTaskDetail();
        bindEvents();
        startAutoRefresh();
    }
    
    // 绑定事件
    function bindEvents() {
        // 日志操作
        $('#refreshLogs').on('click', loadTaskLogs);
        $('#downloadLogs').on('click', downloadLogs);
        $('#clearLogs').on('click', clearLogs);
        $('#autoRefreshLogs').on('change', toggleAutoRefreshLogs);
        
        // 任务操作
        $('#cancelTask').on('click', function() {
            $('#cancelTaskModal').modal('show');
        });
        $('#retryTask').on('click', function() {
            $('#retryTaskModal').modal('show');
        });
        $('#downloadResults').on('click', downloadResults);
        $('#exportTask').on('click', exportTask);
        
        // 模态框确认
        $('#confirmCancelTask').on('click', cancelTask);
        $('#confirmRetryTask').on('click', retryTask);
        
        // 文件操作
        $(document).on('click', '.download-file', function() {
            const fileId = $(this).data('file-id');
            downloadFile(fileId);
        });
        $(document).on('click', '.preview-file', function() {
            const fileId = $(this).data('file-id');
            previewFile(fileId);
        });
    }
    
    // 获取任务ID
    function getTaskIdFromUrl() {
        const pathParts = window.location.pathname.split('/');
        return pathParts[pathParts.length - 2]; // 假设URL格式为 /tasks/{id}/
    }
    
    // 加载任务详情
    function loadTaskDetail() {
        $.ajax({
            url: `/api/tasks/${taskId}/`,
            method: 'GET',
            success: function(task) {
                renderTaskDetail(task);
                loadTaskFiles(task.id);
                loadTaskLogs();
                loadTaskTimeline();
            },
            error: function() {
                showNotification('加载任务详情失败', 'error');
            }
        });
    }
    
    // 渲染任务详情
    function renderTaskDetail(task) {
        $('#taskName').text(task.name || '未命名任务');
        $('#taskDescription').text(task.description || '无描述');
        $('#taskId').text(task.id);
        $('#taskCreatedAt').text(formatDate(task.created_at));
        $('#taskCreatedTime').text(formatDate(task.created_at));
        $('#taskStartTime').text(task.started_at ? formatDate(task.started_at) : '-');
        $('#taskEndTime').text(task.completed_at ? formatDate(task.completed_at) : '-');
        $('#taskDuration').text(calculateDuration(task.started_at, task.completed_at));
        $('#taskTemplate').text(task.template_name || '-');
        $('#taskOutputFormat').text(task.output_format || '-');
        
        // 状态和优先级
        updateTaskStatus(task.status);
        updateTaskPriority(task.priority);
        
        // 进度
        updateTaskProgress(task.progress || 0);
        
        // 操作按钮
        updateActionButtons(task.status);
    }
    
    // 更新任务状态
    function updateTaskStatus(status) {
        const statusElement = $('#taskStatus');
        statusElement.removeClass('pending processing completed failed cancelled');
        statusElement.addClass(status);
        statusElement.text(getStatusText(status));
    }
    
    // 更新任务优先级
    function updateTaskPriority(priority) {
        const priorityElement = $('#taskPriority');
        priorityElement.removeClass('low medium high urgent');
        priorityElement.addClass(priority);
        priorityElement.text(getPriorityText(priority));
    }
    
    // 更新任务进度
    function updateTaskProgress(progress) {
        $('#taskProgress').text(progress + '%');
        $('#progressBar').css('width', progress + '%');
        
        // 更新步骤指示器
        const steps = Math.floor(progress / 20) + 1;
        $('.step').removeClass('completed active');
        
        for (let i = 1; i <= 5; i++) {
            const step = $(`.step[data-step="${i}"]`);
            if (i < steps) {
                step.addClass('completed');
            } else if (i === steps) {
                step.addClass('active');
            }
        }
        
        // 更新进度消息
        updateProgressMessage(progress);
    }
    
    // 更新进度消息
    function updateProgressMessage(progress) {
        let message = '';
        if (progress < 20) {
            message = '正在上传文件...';
        } else if (progress < 40) {
            message = '正在解析数据...';
        } else if (progress < 60) {
            message = '正在应用模板...';
        } else if (progress < 80) {
            message = '正在生成数据...';
        } else if (progress < 100) {
            message = '正在完成任务...';
        } else {
            message = '任务已完成';
        }
        $('#progressMessage').text(message);
    }
    
    // 更新操作按钮
    function updateActionButtons(status) {
        $('#cancelTask, #retryTask, #downloadResults').hide();
        
        switch (status) {
            case 'pending':
            case 'processing':
                $('#cancelTask').show();
                break;
            case 'completed':
                $('#downloadResults').show();
                $('#retryTask').show();
                break;
            case 'failed':
            case 'cancelled':
                $('#retryTask').show();
                break;
        }
    }
    
    // 加载任务文件
    function loadTaskFiles(taskId) {
        $.ajax({
            url: `/api/tasks/${taskId}/files/`,
            method: 'GET',
            success: function(data) {
                renderSourceFiles(data.source_files || []);
                renderResultFiles(data.result_files || []);
            },
            error: function() {
                console.error('加载任务文件失败');
            }
        });
    }
    
    // 渲染源文件
    function renderSourceFiles(files) {
        const container = $('#sourceFiles');
        container.empty();
        
        if (files.length === 0) {
            container.html('<div class="text-center py-3 text-muted">无源文件</div>');
            return;
        }
        
        files.forEach(file => {
            const fileItem = createFileItem(file);
            container.append(fileItem);
        });
    }
    
    // 渲染结果文件
    function renderResultFiles(files) {
        const container = $('#resultFiles');
        const noFilesMsg = $('#noResultFiles');
        
        container.empty();
        
        if (files.length === 0) {
            noFilesMsg.show();
            return;
        }
        
        noFilesMsg.hide();
        files.forEach(file => {
            const fileItem = createFileItem(file);
            container.append(fileItem);
        });
    }
    
    // 创建文件项
    function createFileItem(file) {
        const fileType = getFileType(file.name);
        const fileIcon = getFileIcon(fileType);
        
        return $(`
            <div class="file-item">
                <div class="file-icon ${fileType}">
                    <i class="fas ${fileIcon}"></i>
                </div>
                <div class="file-info">
                    <div class="file-name" title="${file.name}">${file.name}</div>
                    <div class="file-meta">
                        ${formatFileSize(file.size)} • ${formatDate(file.created_at)}
                    </div>
                </div>
                <div class="file-actions">
                    <button type="button" class="btn btn-sm btn-outline-primary preview-file" data-file-id="${file.id}" title="预览">
                        <i class="fas fa-eye"></i>
                    </button>
                    <button type="button" class="btn btn-sm btn-outline-success download-file" data-file-id="${file.id}" title="下载">
                        <i class="fas fa-download"></i>
                    </button>
                </div>
            </div>
        `);
    }
    
    // 加载任务日志
    function loadTaskLogs() {
        $.ajax({
            url: `/api/tasks/${taskId}/logs/`,
            method: 'GET',
            success: function(data) {
                renderTaskLogs(data.logs || []);
            },
            error: function() {
                console.error('加载任务日志失败');
            }
        });
    }
    
    // 渲染任务日志
    function renderTaskLogs(logs) {
        const container = $('#logContainer');
        container.empty();
        
        if (logs.length === 0) {
            container.html('<div class="log-line info">暂无日志</div>');
            return;
        }
        
        logs.forEach(log => {
            const logLine = $(`
                <div class="log-line ${log.level}">
                    [${formatDate(log.timestamp)}] ${log.message}
                </div>
            `);
            container.append(logLine);
        });
        
        // 滚动到底部
        container.scrollTop(container[0].scrollHeight);
    }
    
    // 加载任务时间线
    function loadTaskTimeline() {
        $.ajax({
            url: `/api/tasks/${taskId}/timeline/`,
            method: 'GET',
            success: function(data) {
                renderTaskTimeline(data.timeline || []);
            },
            error: function() {
                console.error('加载任务时间线失败');
            }
        });
    }
    
    // 渲染任务时间线
    function renderTaskTimeline(timeline) {
        const container = $('#taskTimeline');
        container.empty();
        
        if (timeline.length === 0) {
            container.html('<div class="text-muted">暂无时间线数据</div>');
            return;
        }
        
        timeline.forEach(item => {
            const timelineItem = $(`
                <div class="timeline-item">
                    <div class="timeline-content">
                        <div class="timeline-time">${formatDate(item.timestamp)}</div>
                        <div class="timeline-title">${item.title}</div>
                        <div class="timeline-desc">${item.description}</div>
                    </div>
                </div>
            `);
            container.append(timelineItem);
        });
    }
    
    // 开始自动刷新
    function startAutoRefresh() {
        autoRefreshInterval = setInterval(function() {
            loadTaskDetail();
        }, 10000); // 每10秒刷新一次
        
        toggleAutoRefreshLogs();
    }
    
    // 切换自动刷新日志
    function toggleAutoRefreshLogs() {
        if (logRefreshInterval) {
            clearInterval(logRefreshInterval);
            logRefreshInterval = null;
        }
        
        if ($('#autoRefreshLogs').is(':checked')) {
            logRefreshInterval = setInterval(loadTaskLogs, 5000); // 每5秒刷新日志
        }
    }
    
    // 任务操作
    function cancelTask() {
        $.ajax({
            url: `/api/tasks/${taskId}/cancel/`,
            method: 'POST',
            success: function() {
                showNotification('任务已取消', 'success');
                $('#cancelTaskModal').modal('hide');
                loadTaskDetail();
            },
            error: function() {
                showNotification('取消任务失败', 'error');
            }
        });
    }
    
    function retryTask() {
        const useOriginalFiles = $('#useOriginalFiles').is(':checked');
        const useOriginalSettings = $('#useOriginalSettings').is(':checked');
        
        $.ajax({
            url: `/api/tasks/${taskId}/retry/`,
            method: 'POST',
            data: {
                use_original_files: useOriginalFiles,
                use_original_settings: useOriginalSettings
            },
            success: function(data) {
                showNotification('任务已重新提交', 'success');
                $('#retryTaskModal').modal('hide');
                // 跳转到新任务
                window.location.href = `/tasks/${data.new_task_id}/`;
            },
            error: function() {
                showNotification('重试任务失败', 'error');
            }
        });
    }
    
    function downloadResults() {
        window.open(`/api/tasks/${taskId}/download/`, '_blank');
    }
    
    function exportTask() {
        window.open(`/api/tasks/${taskId}/export/`, '_blank');
    }
    
    function downloadLogs() {
        window.open(`/api/tasks/${taskId}/logs/download/`, '_blank');
    }
    
    function clearLogs() {
        if (confirm('确定要清除日志吗？')) {
            $.ajax({
                url: `/api/tasks/${taskId}/logs/clear/`,
                method: 'POST',
                success: function() {
                    showNotification('日志已清除', 'success');
                    loadTaskLogs();
                },
                error: function() {
                    showNotification('清除日志失败', 'error');
                }
            });
        }
    }
    
    function downloadFile(fileId) {
        window.open(`/api/files/${fileId}/download/`, '_blank');
    }
    
    function previewFile(fileId) {
        window.open(`/files/${fileId}/preview/`, '_blank');
    }
    
    // 工具函数
    function getStatusText(status) {
        const statusMap = {
            'pending': '等待中',
            'processing': '处理中',
            'completed': '已完成',
            'failed': '失败',
            'cancelled': '已取消'
        };
        return statusMap[status] || status;
    }
    
    function getPriorityText(priority) {
        const priorityMap = {
            'low': '低',
            'medium': '中',
            'high': '高',
            'urgent': '紧急'
        };
        return priorityMap[priority] || priority;
    }
    
    function getFileType(filename) {
        const ext = filename.split('.').pop().toLowerCase();
        if (['xlsx', 'xls'].includes(ext)) return 'excel';
        if (ext === 'csv') return 'csv';
        if (ext === 'txt') return 'txt';
        return 'other';
    }
    
    function getFileIcon(type) {
        const iconMap = {
            'excel': 'fa-file-excel',
            'csv': 'fa-file-csv',
            'txt': 'fa-file-alt',
            'other': 'fa-file'
        };
        return iconMap[type] || 'fa-file';
    }
    
    function formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }
    
    function formatDate(dateString) {
        if (!dateString) return '-';
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', {hour: '2-digit', minute: '2-digit', second: '2-digit'});
    }
    
    function calculateDuration(startTime, endTime) {
        if (!startTime) return '-';
        if (!endTime) {
            // 计算到现在的时长
            endTime = new Date().toISOString();
        }
        
        const start = new Date(startTime);
        const end = new Date(endTime);
        const duration = end - start;
        
        const hours = Math.floor(duration / (1000 * 60 * 60));
        const minutes = Math.floor((duration % (1000 * 60 * 60)) / (1000 * 60));
        const seconds = Math.floor((duration % (1000 * 60)) / 1000);
        
        if (hours > 0) {
            return `${hours}小时${minutes}分钟`;
        } else if (minutes > 0) {
            return `${minutes}分钟${seconds}秒`;
        } else {
            return `${seconds}秒`;
        }
    }
    
    function showNotification(message, type = 'info') {
        console.log(`${type}: ${message}`);
        // 临时使用alert，实际项目中应该使用更好的通知组件
        if (type === 'error') {
            showError('错误: ' + message);
        }
    }
    
    // 页面卸载时清理定时器
    $(window).on('beforeunload', function() {
        if (autoRefreshInterval) {
            clearInterval(autoRefreshInterval);
        }
        if (logRefreshInterval) {
            clearInterval(logRefreshInterval);
        }
    });
});
</script>
{% endblock %}